package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author Gareth Cao
 * @date 2022/6/15 20:42
 */
public class WmTokenInterceptor implements HandlerInterceptor {

    /**
     * 方法之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //0.判断是否是登录
        System.out.println(request.getRequestURI());//打印路径
        if(request.getRequestURI().contains("/login")){
            //放行
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        //1 从请求头中获取token
        String token = request.getHeader("token");
        //2 解析token，获取用户id
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        Object id = claimsBody.get("id");
        //jdk8之后的特性
        Optional<Object> optional = Optional.ofNullable(id);
        if (optional.isPresent()) {
            //3 存入threadLocal中
            WmUser wmUser = new WmUser();
            wmUser.setId((Integer) id);
            WmThreadLocalUtil.setUser(wmUser);
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 方法之后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("清理threadLocal信息");
        WmThreadLocalUtil.remove();
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
